package com.wtcrazy.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wtcrazy.dao.FilesMapper;
import com.wtcrazy.entity.Files;
import com.wtcrazy.service.IFilesService;
import com.wtcrazy.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


@Slf4j
@Service
public class FilesServiceImpl extends ServiceImpl<FilesMapper, Files> implements IFilesService {
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");
    @Value("${Files.upload.path}")
    private String fileSavePath;
    @Value("${server.IP}")
    private String serverIP;


    @Override
    public JsonResult upload(MultipartFile file, HttpServletRequest req) {//MultipartFile是SpringMVC提供简化上传操作的工具类
        String directory = simpleDateFormat.format(new Date());
//        File dir = new File(fileSavePath + directory);//按照时间保存文件【保存静态服务器的指定位置】
        //得到web服务器所运行的目录,是动态变化的【部署之后就不变了】
        File dir = new File(req.getServletContext().getRealPath("/upload/") + directory);//按照时间保存文件
        //本机上:dir="C:\\Users\\沐白\\AppData\\Local\\Temp\\tomcat-docbase.700571094310578453.8081\\upload\\2023\\08\\05"
        if (!dir.exists()) {
            dir.mkdirs();//可以创建多级文件
        }
//        log.info("图片上传,保存位置:" + webSavePath + directory);
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));//后缀
        String newFileName = UUID.randomUUID().toString().replace("-", "") + suffix;
        File newFile = new File(dir + "/" + newFileName);//文件路径
        System.out.println("------------保存本机的磁盘位置" + newFile);
        try {
            file.transferTo(newFile);//request.getServerName() 可以返回当前页面所在的服务器的名字
            //获取协议、服务器IP、端口号、工程路径
            //本机上basePath:  http://192.168.2.161:8081
            //虚拟路径/files/
            String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/files/" + directory + newFileName;
            log.info("图片上传,访问url:" + url);
            return JsonResult.builder().result(url).message("上传成功").code("1").build();
        } catch (IOException e) {
            return JsonResult.builder().result(null).message("上传失败").code("-1").build();
        }
    }
}
